<?php
namespace app\Services\admin;


use app\models\Room;
use app\models\Seat;
use app\models\User;
use yii;
use app\models\Ivtcode;
use yii\data\Pagination;
use app\Services\ApiService;


class IvtcodeService extends ApiService
{
    public $line = [ 14,14,16,19,19,21,21,21,21,21,21,21,21 ];

    /**
     * @return Service_Pay
     */
    public static function getInstance()
    {
        return parent::getInstance();
    }

    /**
     * 获取邀请码列表
     */
    public function getCodeList($req){
        $limit = !empty($req['num'])?$req['num']:10;
        $offset = !empty($req['page'])?($req['page']-1)*$limit:0;
        $where = ['isDelete'=>0];

        if (!empty($req['code'])){
            $where['code'] = $req['code'];
        }

        $model = Ivtcode::find()
            ->select('ID,code,createtime,roomID,row,col,expire,roomID,binging,used')
            ->where($where)
            ->orderBy('ID DESC');
        $totalCount  = $model->count();
        if (!$totalCount){
            return ['code'=>200,'message'=>'暂无数据'];
        }
        $pages = new Pagination(['totalCount' => $model->count()]);
        $list = $model->offset($offset)
            ->orderBy('ID DESC')
            ->limit($limit)
            ->asArray()
            ->all();
        foreach ($list AS &$item){
            $item['seat'] = '';
            if (!empty($item['row']) && !empty($item['col'])){
                $item['seat'] = $item['row']."排".$item['col']."座";
            }
            unset($item['line'],$item['row']);
            # 生成日期
            $item['createtime'] = substr($item['createtime'],0,10);
            # 绑定用户
            if (!empty($item['binging'])){
                $user = User::find()
                    ->where(['ID'=>intval($item['binging'])])
                    ->select('Name')
                    ->asArray()
                    ->one();
                $item['binging'] = $user['Name'];
            }else{
                $item['binging'] = '';
            }
        }
        if (empty($list)){
            return ['code'=>200,'message'=>'暂无数据'];
        }
        return ['code'=>200,'data'=>['list'=>$list,'totalCount'=>intval($totalCount)]];
    }

    /**
     * 生成单个二维码
     */
    public function createSingleCode(){
        $randstr = $this->createCode();
        return ['code'=>200,'data'=>['code'=>$randstr]];
    }

    /**
     * 保存邀请码的设置
     */
    public function saveCodeSetting($info){
        # 验证二维码是否重复
        $count = Ivtcode::find()
            ->where(['code'=>$info['code']])
            ->count();
        if ($count){
            return ['code'=>-1,'message'=>'邀请码重复,请重新生成'];
        }

        # 验证房间的人数
        $room=Room::find()
            ->where(['ID'=>$info['roomID']])
            ->select('codeCount')
            ->asArray()
            ->one();
//        if ($room['codeCount'] >= 250){
//            return ['code'=>-1,'message'=>'该房间人数'];
//        }
        # 座位号是否重复
        $count = Ivtcode::find()
            ->where(['roomID'=>$info['roomID'],'row'=>$info['row'],'col'=>$info['col'],'isDelete'=>0])
            ->count();

        if ($count){
            return ['code'=>-1,'message'=>'该座位号已生成邀请码，请重新选在座位'];
        }

        # 验证col 是否符合规范
        if ($info['col']>$this->line[intval($info['row'])-1]){
            return ['code'=>-1,'message'=>'座位号有误,请重新输入'];
        }

        # 验证用户是否 绑定其他code
        if (!empty($info['userID'])){
            # 用户是否存在
            $user = User::find()->where(['ID'=>$info['userID']])->count();
            if (empty($user)) {
                return ['code'=>-1,'message'=>'用户不存在'];
            }
            $user_bind=Ivtcode::find()
                ->select('ID,used')
                ->where(['binging'=>$info['userID'],'isDelete'=>0])
                ->asArray()->one();
            if (!empty($user_bind)){
                # 1.解除绑定关系
                Yii::$app->db->createCommand()->update('`pltf.ivtcode`', ['binging'=> 0],['ID'=>$user_bind['ID']] )->execute();
                # 2. 已使用：用户等级置为普通      2	未使用：不处理
                if ($user_bind['used']){
                    Yii::$app->db->createCommand()->update('`user.user`', ['Level'=> 1],['ID'=>$info['userID']] )->execute();
                }
            }
        }
        $insert = [
            'code'      => $info['code'],
            'roomID'    => $info['roomID'],
            'row'       => $info['row'],
            'col'       => $info['col'],
            'expire'    => $info['expire'],
            'level'     => $info['level'],
            'createtime'=>date("Y-m-d H:i:s",time())
        ];
        if (!empty($info['userID'])){
            $insert['binging'] = $info['userID'];
        }
        $res = Yii::$app->db->createCommand()->insert('`pltf.ivtcode`', $insert )->execute();
        if ($res){
            # seat 表  对应位置 置为 -1
            # 找到对应行数据
            $seat = Seat::find()
                ->where(['line'=>$info['row'],'roomID'=>$info['roomID']])
                ->select('ID,seatdate')
                ->asArray()
                ->one();
            $seat_arr = explode('/',$seat['seatdate']);
            $seat_arr[intval($info['col'])-1] = -1;
            $seatdate = implode('/',$seat_arr);
            Yii::$app->db->createCommand()->update('`pltf.seat`', ['seatdate'=>$seatdate],['line'=>$info['row'],'roomID'=>$info['roomID']] )->execute();
            # room 表 codeCount  +1
            Yii::$app->db->createCommand()->update('`pltf.room`', ['codeCount'=> intval($room['codeCount']+1)],['ID'=>$info['roomID']] )->execute();
            return ['code'=>200,'message'=>'保存成功'];
        }else{
            return ['code'=>-1,'message'=>'保存失败'];
        }
    }

    /**
     * 批量生成邀请码
     */
    public function createBatchCode($info){
        # 查询该房间 现有的邀请码个数
        $room = Room::find()
            ->where(['ID'=>$info['roomID']])
            ->select('codeCount')
            ->asArray()
            ->one();
//        if (250-intval($room['codeCount']) < $info['count'] ){
//            return ['code'=>-1,'message'=>'该房间不允许生成该数量的邀请码'];
//        }
        $time = date("Y-m-d H:i:s",time());
        $code_list = [];
        for ($i=0;$i<intval($info['count']);$i++){
            $code = $this->createCode();
            $insert = [
                'code'      => $code,
                'roomID'    => $info['roomID'],
                'expire'    => $info['expire'],
                'level'     => $info['level'],
                'createtime'=> $time
            ];
            $res = Yii::$app->db->createCommand()->insert('`pltf.ivtcode`', $insert )->execute();
            if($res){
                $insert_id = Yii::$app->db->getLastInsertId();
                $code_list[]=['ID'=>$insert_id,'code'=>$code];
            }else{
                $i --;
            }
        }
        if (!empty($res) && $res){
            # 房间 codeCount +count
            $nowC = $room['codeCount'] + $info['count'];
            Yii::$app->db->createCommand()->update('`pltf.room`', ['codeCount'=>$nowC],['ID'=>$info['roomID']])->execute();
            return ['code'=>200,'message'=>'生成成功','data'=>$code_list];
        }else{
            return ['code'=>-1,'message'=>'生成失败'];
        }
    }

    /**
     * 导出二维码
     */
    public function exportCodeList($id_str){
        $id_arr = explode(',',$id_str);
        $list = Ivtcode::find()
            ->where(['in','ID',$id_arr])
            ->select('ID, code')
            ->asArray()
            ->all();
        return ['code'=>200,'data'=>$list];
    }


    /**
     * 删除邀请码
     */
    public function delCode($id){
        $code = Ivtcode::find()
            ->where(['ID'=>$id])
            ->select('expire')
            ->asArray()
            ->one();
        if (empty($code)){
            return ['code'=>-1,'message'=>'邀请码不存在,请检查参数'];
        }

        # 邀请码是否过期
        if ($code['expire'] >= date("Y-m-d H:i:s",time()) ){
            return ['code'=>-1,'message'=>'邀请码未过期，不允许删除'];
        }

        $update = ['isDelete'=>1];
        $where  = ['ID'=>$id];
        $res = Yii::$app->db->createCommand()->update('`pltf.ivtcode`', $update, $where )->execute();
        if ($res){
            return ['code'=>200,'message'=>'删除成功'];
        }else{
            return ['code'=>-1,'message'=>'删除失败'];
        }
    }


    /**
     * 生成邀请码
     * @return string
     */
    public function createCode(){
        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<8;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }




}